﻿/*
    This file is part of nDoctor Light

    NDoctor is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    NDoctor is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with NDoctor.  If not, see <http://www.gnu.org/licenses/>.
*/
namespace Probel.Ldoc.Shell
{
    using System.ComponentModel;
    using System.Deployment.Application;
    using System.Linq;
    using System.Threading;
    using System.Threading.Tasks;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Input;

    using Probel.Ldoc.Services.Dto;
    using Probel.Ldoc.Shell.Properties;
    using Probel.Ldoc.Shell.Tools;
    using Probel.Ldoc.Shell.Views;
    using Probel.Ldoc.Views;
    using Probel.Ldoc.Views.Helpers;
    using Probel.Ldoc.Views.Pages;
    using Probel.Ldoc.Views.ToolBoxes;
    using Probel.Mvvm.DataBinding;
    using Probel.Mvvm.Gui;
    using Probel.Mvvm.Gui.FileServices;

    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class ShellView : Window
    {
        #region Constructors

        public ShellView()
        {
            InitializeComponent();
        }

        #endregion Constructors

        #region Properties

        private PatientCardDto CurrentPatient
        {
            get;
            set;
        }

        #endregion Properties

        #region Methods

        private void CheckUpdate()
        {
            this.statusBar.Visibility = Visibility.Collapsed;
            var scheduler = TaskScheduler.FromCurrentSynchronizationContext();

            if (ApplicationDeployment.IsNetworkDeployed)
            {
                Task.Run(() => ApplicationDeployment.CurrentDeployment.CheckForUpdate())
                    .ContinueWith(t =>
                    {
                        if (t.Result)
                        {
                            var deployment = ApplicationDeployment.CurrentDeployment;
                            this.statusBar.Visibility = Visibility.Visible;
                            ViewService.MessageBox.Question(Messages.Msg_NotifyUpdate);

                            deployment.UpdateProgressChanged += Deployment_UpdateProgressChanged;
                            deployment.UpdateCompleted += Deployment_UpdateCompleted;
                            deployment.UpdateAsync();

                        }
                    }, CancellationToken.None, TaskContinuationOptions.NotOnFaulted, scheduler)
                    .ContinueWith(t => AppContext.Instance.ViewModelFactory.ErrorService.HandleError(t.Exception), CancellationToken.None, TaskContinuationOptions.OnlyOnFaulted, scheduler);
            }
        }

        private void Click_About(object sender, RoutedEventArgs e)
        {
            var view = new AboutView();
            view.Owner = ViewService.RootWindow;
            view.ShowDialog();
        }

        private void Click_Close(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void Click_EditPatient(object sender, RoutedEventArgs e)
        {
            this.GoToPatientEditor();
        }

        private void Click_ExtractPictures(object sender, RoutedEventArgs e)
        {
            this.GoToExtractPictures();
        }

        private void Click_FindIncoherences(object sender, RoutedEventArgs e)
        {
            var view = new IncoherencesView(AppContext.Instance.ViewModelFactory.BuildIncoherenceViewModel());
            this.GoTo(view);
        }

        private void Click_NewPatient(object sender, RoutedEventArgs e)
        {
            this.GoToNewPatient();
        }

        private void Click_RecordEditor(object sender, RoutedEventArgs e)
        {
            this.GoToRecordEditor();
        }

        private void Click_Search(object sender, RoutedEventArgs e)
        {
            this.GoToSearch();
        }

        private void Click_Settings(object sender, RoutedEventArgs e)
        {
            var view = new SettingsView();
            view.Owner = this;
            view.ShowDialog();
            this.ManageMenuVisibility();
            this.SetMenuTextVisibility();
        }

        private void CommandOpen_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = true;
        }

        private void CommandOpen_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            this.CurrentPatient = e.Parameter as PatientCardDto;
            SetMenuForLoadedPatient(true);
        }

        private void Deployment_UpdateCompleted(object sender, AsyncCompletedEventArgs e)
        {
            ViewService.MessageBox.Information(Messages.Msg_UpdateComplete);
            this.statusBar.Visibility = Visibility.Collapsed;
        }

        private void Deployment_UpdateProgressChanged(object sender, DeploymentProgressChangedEventArgs e)
        {
            this.updateProgress.Value = e.ProgressPercentage;
        }

        private void GoTo<T>(T view)
        {
            if (!this.PrenavigationProcess())
            {
                this.mainFrame.Navigate(view);
                if (view is IInitialisable) { (view as IInitialisable).Initialise(); }
            }
        }

        private void GoToExtractPictures()
        {
            var view = new ExtractPicturesView(AppContext.Instance.ViewModelFactory.BuildExtractPicturesViewModel());
            view.ShowDialog();
        }

        private void GoToNewPatient()
        {
            var view = new CreateInstantPatientView(AppContext.Instance.ViewModelFactory.BuildCreatePatientViewModel());
            view.Owner = this;
            var dr = view.ShowDialog();

            if (dr.HasValue && view.CreatedPatient != null)
            {
                this.CurrentPatient = view.CreatedPatient;
                SetMenuForLoadedPatient(true);

                // If user asked to load this patient after creation,
                // go to edition view
                if (dr.Value) { this.GoToPatientEditor(); }
            }
        }

        private void GoToPatientEditor()
        {
            var view = new PatientEditorView(AppContext.Instance.ViewModelFactory.BuildEditPatientViewModel(this.CurrentPatient, new CriterionFactory()));
            this.GoTo(view);
        }

        private void GoToRecordEditor()
        {
            var view = new RecordEditorView(AppContext.Instance.ViewModelFactory.BuildRecordEditorViewModel(this.CurrentPatient));
            this.GoTo(view);
        }

        private void GoToSearch()
        {
            var view = new SearchView(AppContext.Instance.ViewModelFactory.BuildSearchViewModel(new CriterionFactory()));
            this.GoTo(view);
        }

        private void ManageMenuVisibility()
        {
            this.ribbon.Visibility = (CoreSettings.Default.IsRibbonVisible)
                ? Visibility.Visible
                : Visibility.Collapsed;
            this.toolboxTray.Visibility = (CoreSettings.Default.IsRibbonVisible)
                ? Visibility.Collapsed
                : Visibility.Visible;
        }

        /// <summary>
        /// Check whether the previous navigation implements a saving workflow and executes it if necessary.
        /// </summary>
        /// <returns></returns>
        private bool PrenavigationProcess()
        {
            var current = this.mainFrame.NavigationService.Content as ISavable;

            if (current != null && current.IsModified)
            {
                return current.ManageSaveFlow();
            }
            return false;
        }

        private void SetMenuForLoadedPatient(bool isPatientLoaded)
        {
            this.groupNavigation.IsEnabled = isPatientLoaded;
            this.btnRecordEditor.Visibility
                = this.btnEditPatient.Visibility
                = this.viewMenu.Visibility
                = (isPatientLoaded) ? Visibility.Visible : Visibility.Collapsed;
        }

        private void SetMenuTextVisibility()
        {
            foreach (var item in this.mainToolbar.Items)
            {
                if (item is Button)
                {
                    var dp = (item as Button).Content;
                    if (dp is DockPanel)
                    {
                        foreach (var child in (dp as DockPanel).Children)
                        {
                            if (child is TextBlock)
                            {
                                (child as TextBlock).Visibility = CoreSettings.Default.MenuTextVisibility;
                            }
                        }
                    }
                }
            }
        }

        private void ShellView_KeyUp(object sender, KeyEventArgs e)
        {
            #region Control
            if (e.KeyboardDevice.Modifiers == ModifierKeys.Control)
            {
                if (e.Key == Key.N) { this.GoToNewPatient(); }
            }
            #endregion
            #region Control + Shift
            else if (e.KeyboardDevice.Modifiers == ModifierKeys.Control
                      && e.KeyboardDevice.Modifiers == ModifierKeys.Shift)
            {
                if (e.Key == Key.F) { this.GoToSearch(); }
            }
            #endregion
            #region One key
            else
            {
                if (e.Key == Key.F3) { this.GoToSearch(); }
                else if (e.Key == Key.F6) { this.GoToRecordEditor(); }
                else if (e.Key == Key.F7) { this.GoToPatientEditor(); }
            }
            #endregion
        }

        private void Window_Closing(object sender, CancelEventArgs e)
        {
            #if !DEBUG
            e.Cancel = !ViewService.MessageBox.Question(Messages.Msg_Quit);
            #endif
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            this.CheckUpdate();

            this.sideColumn.Width = new GridLength(0);
            ManageMenuVisibility();
            #if DEBUG
            this.CurrentPatient = AppContext.Instance.ViewModelFactory.PatientService.GetPatients(new CriterionFactory().Build("Wautier")).ElementAt(0);
            #else
            this.SetMenuForLoadedPatient(false);
            #endif
        }

        #endregion Methods
    }
}